<?php

namespace SidToken\Controller;

use Common\Model\MemberModel;
use SidToken\Crontab\MiningCrontab;
use SidToken\Model\QueueLogModel;
use SidToken\Model\QueueModel;
use SidToken\Model\SidTrxErrModel;
use SidToken\Utils\TrxRpc;

class QueueController extends BaseController
{
    protected function _initialize()
    {
        $whiteListConfig = C("WHITELIST");
        $crontabWhitelist = $whiteListConfig['crontab'];
        if (!in_array(getRealIp(), $crontabWhitelist)) {
            exit("permission deny:".getRealIp());
        }
    }


    public function runTask()
    {
        crontab_log("crontab of sid ======");
        $this->doDynamicQueue(60);
        $this->continuedMining();
        $this->mining();
        crontab_log("crontab of sid end ======");
    }

    /**
     * 持续挖矿； 直到设置的时间达到，否则连续挖矿
     * @param int $end
     */
    private function continuedMining($end = 1618502400)
    {
        $MiningCrontab = new MiningCrontab();

        $status = $MiningCrontab->queryStatus();
        //echo "timeeeee:".intval($status['time']) - intval($end);
        if ($status['status'] == "finish") {
            $time = $status['time'];
            if ($time) {
                //$end = 1618502400;
                if (intval($time) - intval($end) >= 0) {
                    return;
                } else {
                    $time = $time + 86400;
                    $this->startMining($time);
                }
            }
        }
    }

    public function querystatus()
    {
        $MiningCrontab = new MiningCrontab();
        $status = $MiningCrontab->queryStatus();
        $this->jsuccess($status);
    }

//    /**
//     * 对余额进行快照 已作废
//     * @param int $time
//     */
//    public function syncBalance($time = 60)
//    {
////        $key = "syncBalance";
////        $rs = $this->timeToDoTask($key, $time);//每日执行一次
////        if (!$rs) {
////            return true;
////        }
//        $Member = new MemberModel();
//        $MemberWallet = new MemberWalletUtil();
//        $lists = $Member->field("uid")->where(['sync_data' => 0, 'status' => 1, 'wallet_address' => ['neq', ""]])->limit(40)->select();
//        foreach ($lists as $val) {
//            $uid = $val['uid'];
//            $MemberWallet->syncBalance($uid);
//        }
//        $this->jsuccess();
//    }

    public function startMining($time = "")
    {
        if (!$time) {
            $time = strtotime(date("Ymd"));
        }
        //$time = strtotime(date("Ymd",$time));
        $MiningCrontab = new MiningCrontab();
        $result = $MiningCrontab->startMining($time);
        echo json_encode($result);
    }

    public function mining()
    {
        $MiningCrontab = new MiningCrontab();
        $result = $MiningCrontab->mining();
        echo json_encode($result);
    }

    public function solveErr($time = 60)
    {
        $key = "solveErr";
        $rs = $this->timeToDoTask($key, $time);//每日执行一次
        if (!$rs) {
            return true;
        }
        $TrxErrModel = new SidTrxErrModel();
        $TrxErrModel->solveErr();
        return true;
    }

    /**
     * 动态计划任务执行
     * @param int $time
     * @return bool
     * @throws \Exception
     */
    function doDynamicQueue($time = 60)
    {
        $limit = 20;
        $key = "doDynamicQueue";
        $rs = $this->timeToDoTask($key, $time);//每日执行一次
        if (!$rs) {
            return true;
        }

        $stime = microtime(true); #获取程序开始执行的时间

        //查询是否有任务
        $Queue = new QueueModel();
        $map = "status=" . $Queue::STATUS_WAIT . " AND stime<=" . time();

        $lists = $Queue->where($map)->limit($limit)->select();

        if ($lists) {
            foreach ($lists as $val) {
                $url = $val['controller_url'];
                $parameter = json_decode($val['parameter'], true);
                $rs = $rsStr = curlPost($url, $parameter);
                $rs = json_decode($rs, true);
                if ($rs['status'] == 1) {
                    $save = array(
                        'status' => $Queue::STATUS_NORMAL,
                        'etime' => time(),
                        'exe_result' => $rsStr
                    );
                } else {
                    $save = array(
                        'etime' => time(),
                        'exe_result' => $rsStr
                    );
                }
                $Queue->where("id={$val['id']}")->save($save);
            }
            $etime = microtime(true); #获取程序执行结束的时间
            $total = $etime - $stime;   #计算差值
            $QueueLogModel = new QueueLogModel();
            $QueueLogModel->addQueueLog($key, $total);
        }
        return true;
    }
}